"use client";

import { useState, useEffect } from "react";
import { Card, CardContent, CardHeader, CardTitle } from "@/components/ui/card";
import {
  Table,
  TableBody,
  TableCell,
  TableHead,
  TableHeader,
  TableRow,
} from "@/components/ui/table";
import { Input } from "@/components/ui/input";
import { Button } from "@/components/ui/button";
import { Badge } from "@/components/ui/badge";
import { Search, Edit, Trash2 } from "lucide-react";
import {
  AlertDialog,
  AlertDialogAction,
  AlertDialogCancel,
  AlertDialogContent,
  AlertDialogDescription,
  AlertDialogFooter,
  AlertDialogHeader,
  AlertDialogTitle,
  AlertDialogTrigger,
} from "@/components/ui/alert-dialog";
import {
  Select,
  SelectContent,
  SelectItem,
  SelectTrigger,
  SelectValue,
} from "@/components/ui/select";
import {
  Dialog,
  DialogContent,
  DialogDescription,
  DialogFooter,
  DialogHeader,
  DialogTitle,
  DialogTrigger,
} from "@/components/ui/dialog";
import { Label } from "@/components/ui/label";

interface Commodity {
  goodsId: number;
  openId: string;
  goodsName: string;
  ImgUrl: string;
  gDesc: string | null;
  goodsPrice: number;
  goodsAddress: string;
  dvForm: string;
  prcForm: string;
  categoryId: number | null;
  pbTime: string;
  state: number;
  userName: string;
  categoryName: string | null;
}

export default function CommoditiesPage() {
  const [commodities, setCommodities] = useState<Commodity[]>([]);
  const [searchTerm, setSearchTerm] = useState("");
  const [categoryFilter, setCategoryFilter] = useState("all");
  const [isLoading, setIsLoading] = useState(true);
  const [categories, setCategories] = useState<
    { categoryId: number; categoryName: string }[]
  >([]);
  const [isDeleteDialogOpen, setIsDeleteDialogOpen] = useState(false);
  const [commodityToDelete, setCommodityToDelete] = useState<number | null>(
    null
  );
  const [isDialogOpen, setIsDialogOpen] = useState(false);
  const [newCommodity, setNewCommodity] = useState({
    goodsName: "",
    goodsPrice: 0,
    gDesc: "",
    goodsAddress: "",
    categoryId: 0,
    ImgUrl:
      "https://img1.baidu.com/it/u=415449740,540746270&fm=253&fmt=auto&app=138&f=GIF?w=500&h=500",
    dvForm: "送货到寝",
    prcForm: "一口价",
    openId: "admin", // 默认使用管理员 ID
    state: 1,
  });
  const [isEditDialogOpen, setIsEditDialogOpen] = useState(false);
  const [editCommodity, setEditCommodity] = useState<Commodity | null>(null);

  useEffect(() => {
    fetchCommodities();
    fetchCategories();
  }, []);

  const fetchCommodities = async () => {
    try {
      setIsLoading(true);
      const response = await fetch("/api/commodities");

      if (!response.ok) {
        throw new Error("获取商品数据失败");
      }

      const data = await response.json();
      setCommodities(data.commodities);
    } catch (error) {
      console.error("获取商品数据失败:", error);
    } finally {
      setIsLoading(false);
    }
  };

  const fetchCategories = async () => {
    try {
      const response = await fetch("/api/categories");

      if (!response.ok) {
        throw new Error("获取分类数据失败");
      }

      const data = await response.json();
      setCategories(
        data.categories.map((cat: any) => ({
          categoryId: cat.categoryId,
          categoryName: cat.categoryName,
        }))
      );
    } catch (error) {
      console.error("获取分类数据失败:", error);
    }
  };

  // 过滤商品
  const filteredCommodities = commodities.filter((commodity) => {
    const matchesSearch =
      commodity.goodsName.toLowerCase().includes(searchTerm.toLowerCase()) ||
      (commodity.gDesc &&
        commodity.gDesc.toLowerCase().includes(searchTerm.toLowerCase()));

    const matchesCategory =
      categoryFilter === "all" ||
      commodity.categoryId?.toString() === categoryFilter;

    return matchesSearch && matchesCategory;
  });

  const handleCreateCommodity = async () => {
    try {
      if (!newCommodity.goodsName) {
        alert("商品名称不能为空");
        return;
      }

      if (newCommodity.goodsPrice <= 0) {
        alert("商品价格必须大于 0");
        return;
      }

      const response = await fetch("/api/commodities", {
        method: "POST",
        headers: {
          "Content-Type": "application/json",
        },
        body: JSON.stringify(newCommodity),
      });

      if (!response.ok) {
        const errorData = await response.json();
        throw new Error(errorData.error || "创建商品失败");
      }

      // 重置表单并关闭对话框
      setNewCommodity({
        goodsName: "",
        goodsPrice: 0,
        gDesc: "",
        goodsAddress: "",
        categoryId: 0,
        ImgUrl:
          "https://img1.baidu.com/it/u=415449740,540746270&fm=253&fmt=auto&app=138&f=GIF?w=500&h=500",
        dvForm: "送货到寝",
        prcForm: "一口价",
        openId: "admin",
        state: 1,
      });
      setIsDialogOpen(false);

      // 重新获取商品列表
      fetchCommodities();
    } catch (error) {
      console.error("创建商品失败:", error);
      alert(error instanceof Error ? error.message : "创建商品失败");
    }
  };

  const handleEditCommodity = async (editedCommodity: Commodity) => {
    try {
      const response = await fetch(
        `/api/commodities?goodsId=${editedCommodity.goodsId}`,
        {
          method: "PATCH",
          headers: {
            "Content-Type": "application/json",
          },
          body: JSON.stringify(editedCommodity),
        }
      );

      if (!response.ok) {
        const errorData = await response.json();
        console.error("更新商品失败，状态码:", response.status);
        console.error("错误信息:", errorData);
        throw new Error(errorData.error || "更新商品失败");
      }

      setCommodities((prev) =>
        prev.map((item) =>
          item.goodsId === editedCommodity.goodsId ? editedCommodity : item
        )
      );
      setEditCommodity(null);
    } catch (error) {
      console.error("更新商品失败:", error);
      alert("更新商品失败，请稍后重试");
    }
  };

  const handleDeleteCommodity = async (goodsId: number) => {
    try {
      const response = await fetch(`/api/commodities?goodsId=${goodsId}`, {
        method: "DELETE",
      });

      if (!response.ok) {
        const errorData = await response.json();
        console.error("删除商品失败，状态码:", response.status);
        console.error("错误信息:", errorData);
        throw new Error(errorData.error || "删除商品失败");
      }

      // 从本地商品列表中移除已删除的商品
      setCommodities((prev) => prev.filter((item) => item.goodsId !== goodsId));
      setIsDeleteDialogOpen(false);
    } catch (error) {
      console.error("删除商品失败:", error);
      alert("删除商品失败，请稍后重试");
    }
  };

  return (
    <div className="space-y-6">
      <div>
        <h1 className="text-3xl font-bold tracking-tight">商品管理</h1>
        <p className="text-muted-foreground">查看和管理平台商品信息</p>
      </div>

      <Card>
        <CardHeader className="flex flex-row items-center justify-between space-y-0 pb-2">
          <CardTitle className="text-xl font-bold">商品列表</CardTitle>
          <div className="flex items-center space-x-2">
            <div className="relative">
              <Search className="absolute left-2.5 top-2.5 h-4 w-4 text-muted-foreground" />
              <Input
                type="search"
                placeholder="搜索商品..."
                className="pl-8 w-[250px]"
                value={searchTerm}
                onChange={(e) => setSearchTerm(e.target.value)}
              />
            </div>
            <Select value={categoryFilter} onValueChange={setCategoryFilter}>
              <SelectTrigger className="w-[180px]">
                <SelectValue placeholder="所有分类" />
              </SelectTrigger>
              <SelectContent>
                <SelectItem value="all">所有分类</SelectItem>
                {categories.map((category) => (
                  <SelectItem
                    key={category.categoryId}
                    value={category.categoryId.toString()}
                  >
                    {category.categoryName}
                  </SelectItem>
                ))}
              </SelectContent>
            </Select>
            <Dialog open={isDialogOpen} onOpenChange={setIsDialogOpen}>
              <DialogContent>
                <DialogHeader>
                  <DialogTitle>添加新商品</DialogTitle>
                  <DialogDescription>
                    请填写以下信息创建新的商品
                  </DialogDescription>
                </DialogHeader>
                <div className="grid gap-4 py-4">
                  <div className="grid grid-cols-4 items-center gap-4">
                    <Label htmlFor="goodsName" className="text-right">
                      商品名称
                    </Label>
                    <Input
                      id="goodsName"
                      value={newCommodity.goodsName}
                      onChange={(e) =>
                        setNewCommodity({
                          ...newCommodity,
                          goodsName: e.target.value,
                        })
                      }
                      className="col-span-3"
                      required
                    />
                  </div>
                  <div className="grid grid-cols-4 items-center gap-4">
                    <Label htmlFor="goodsPrice" className="text-right">
                      商品价格
                    </Label>
                    <Input
                      id="goodsPrice"
                      type="number"
                      value={newCommodity.goodsPrice}
                      onChange={(e) =>
                        setNewCommodity({
                          ...newCommodity,
                          goodsPrice: parseFloat(e.target.value),
                        })
                      }
                      className="col-span-3"
                      required
                    />
                  </div>
                  <div className="grid grid-cols-4 items-center gap-4">
                    <Label htmlFor="gDesc" className="text-right">
                      商品描述
                    </Label>
                    <Input
                      id="gDesc"
                      value={newCommodity.gDesc}
                      onChange={(e) =>
                        setNewCommodity({
                          ...newCommodity,
                          gDesc: e.target.value,
                        })
                      }
                      className="col-span-3"
                    />
                  </div>
                  <div className="grid grid-cols-4 items-center gap-4">
                    <Label htmlFor="goodsAddress" className="text-right">
                      商品地址
                    </Label>
                    <Input
                      id="goodsAddress"
                      value={newCommodity.goodsAddress}
                      onChange={(e) =>
                        setNewCommodity({
                          ...newCommodity,
                          goodsAddress: e.target.value,
                        })
                      }
                      className="col-span-3"
                      required
                    />
                  </div>
                  <div className="grid grid-cols-4 items-center gap-4">
                    <Label htmlFor="categoryId" className="text-right">
                      商品分类
                    </Label>
                    <select
                      id="categoryId"
                      value={newCommodity.categoryId}
                      onChange={(e) =>
                        setNewCommodity({
                          ...newCommodity,
                          categoryId: parseInt(e.target.value),
                        })
                      }
                      className="col-span-3 flex h-10 w-full rounded-md border border-input bg-background px-3 py-2 text-sm ring-offset-background file:border-0 file:bg-transparent file:text-sm file:font-medium placeholder:text-muted-foreground focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-offset-2 disabled:cursor-not-allowed disabled:opacity-50"
                    >
                      <option value="0">请选择分类</option>
                      {categories.map((category) => (
                        <option
                          key={category.categoryId}
                          value={category.categoryId}
                        >
                          {category.categoryName}
                        </option>
                      ))}
                    </select>
                  </div>
                  <div className="grid grid-cols-4 items-center gap-4">
                    <Label htmlFor="ImgUrl" className="text-right">
                      图片 URL
                    </Label>
                    <Input
                      id="ImgUrl"
                      value={newCommodity.ImgUrl}
                      onChange={(e) =>
                        setNewCommodity({
                          ...newCommodity,
                          ImgUrl: e.target.value,
                        })
                      }
                      className="col-span-3"
                    />
                  </div>
                </div>
                <DialogFooter>
                  <Button
                    variant="outline"
                    onClick={() => setIsDialogOpen(false)}
                  >
                    取消
                  </Button>
                  <Button onClick={handleCreateCommodity}>创建</Button>
                </DialogFooter>
              </DialogContent>
            </Dialog>
          </div>
        </CardHeader>
        <CardContent>
          {isLoading ? (
            <div className="flex justify-center items-center h-[400px]">
              <p>加载中...</p>
            </div>
          ) : (
            <Table>
              <TableHeader>
                <TableRow>
                  <TableHead>商品名称</TableHead>
                  <TableHead>价格</TableHead>
                  <TableHead>分类</TableHead>
                  <TableHead>发布者</TableHead>
                  <TableHead>状态</TableHead>
                  <TableHead className="text-right">操作</TableHead>
                </TableRow>
              </TableHeader>
              <TableBody>
                {filteredCommodities.length === 0 ? (
                  <TableRow>
                    <TableCell colSpan={6} className="text-center h-24">
                      未找到匹配的商品
                    </TableCell>
                  </TableRow>
                ) : (
                  filteredCommodities.map((commodity) => (
                    <TableRow key={commodity.goodsId}>
                      <TableCell className="font-medium">
                        <div className="flex items-center space-x-2">
                          <img
                            src={commodity.ImgUrl}
                            alt={commodity.goodsName}
                            className="h-10 w-10 rounded object-cover"
                          />
                          <span>{commodity.goodsName}</span>
                        </div>
                      </TableCell>
                      <TableCell>¥{commodity.goodsPrice.toFixed(2)}</TableCell>
                      <TableCell>{commodity.categoryName || "-"}</TableCell>
                      <TableCell>{commodity.userName}</TableCell>
                      <TableCell>
                        <Badge
                          variant={
                            commodity.state === 1 ? "default" : "secondary"
                          }
                        >
                          {commodity.state === 1 ? "在售" : "已下架"}
                        </Badge>
                      </TableCell>
                      <TableCell className="text-right">
                        <Dialog
                          open={
                            isEditDialogOpen &&
                            editCommodity?.goodsId === commodity.goodsId
                          }
                          onOpenChange={(open) => {
                            setIsEditDialogOpen(open);
                            if (!open) setEditCommodity(null);
                          }}
                        >
                          <DialogTrigger asChild>
                            <Button
                              variant="ghost"
                              size="icon"
                              onClick={() => {
                                setEditCommodity({
                                  goodsId: commodity.goodsId,
                                  goodsName: commodity.goodsName,
                                  goodsPrice: commodity.goodsPrice,
                                  categoryId: commodity.categoryId || 0,
                                });
                              }}
                            >
                              <Edit className="h-4 w-4" />
                            </Button>
                          </DialogTrigger>
                          <DialogContent>
                            <DialogHeader>
                              <DialogTitle>编辑商品</DialogTitle>
                              <DialogDescription>
                                修改商品信息
                              </DialogDescription>
                            </DialogHeader>
                            <div className="grid gap-4 py-4">
                              <div className="grid grid-cols-4 items-center gap-4">
                                <Label
                                  htmlFor="goodsName"
                                  className="text-right"
                                >
                                  商品名称
                                </Label>
                                <Input
                                  id="goodsName"
                                  value={editCommodity?.goodsName || ""}
                                  onChange={(e) =>
                                    setEditCommodity((prev) =>
                                      prev
                                        ? { ...prev, goodsName: e.target.value }
                                        : null
                                    )
                                  }
                                  className="col-span-3"
                                />
                              </div>
                              <div className="grid grid-cols-4 items-center gap-4">
                                <Label
                                  htmlFor="goodsPrice"
                                  className="text-right"
                                >
                                  价格
                                </Label>
                                <Input
                                  id="goodsPrice"
                                  type="number"
                                  value={editCommodity?.goodsPrice || 0}
                                  onChange={(e) =>
                                    setEditCommodity((prev) =>
                                      prev
                                        ? {
                                            ...prev,
                                            goodsPrice: parseFloat(
                                              e.target.value
                                            ),
                                          }
                                        : null
                                    )
                                  }
                                  className="col-span-3"
                                />
                              </div>
                              <div className="grid grid-cols-4 items-center gap-4">
                                <Label
                                  htmlFor="categoryId"
                                  className="text-right"
                                >
                                  分类
                                </Label>
                                <Select
                                  value={
                                    editCommodity?.categoryId.toString() || ""
                                  }
                                  onValueChange={(value) =>
                                    setEditCommodity((prev) =>
                                      prev
                                        ? {
                                            ...prev,
                                            categoryId: parseInt(value),
                                          }
                                        : null
                                    )
                                  }
                                >
                                  <SelectTrigger className="col-span-3">
                                    <SelectValue placeholder="选择分类" />
                                  </SelectTrigger>
                                  <SelectContent>
                                    {categories.map((category) => (
                                      <SelectItem
                                        key={category.categoryId}
                                        value={category.categoryId.toString()}
                                      >
                                        {category.categoryName}
                                      </SelectItem>
                                    ))}
                                  </SelectContent>
                                </Select>
                              </div>
                            </div>
                            <DialogFooter>
                              <Button
                                onClick={() =>
                                  editCommodity &&
                                  handleEditCommodity(editCommodity)
                                }
                              >
                                保存更改
                              </Button>
                            </DialogFooter>
                          </DialogContent>
                        </Dialog>
                        <AlertDialog
                          open={
                            isDeleteDialogOpen &&
                            commodityToDelete === commodity.goodsId
                          }
                          onOpenChange={(open) => {
                            setIsDeleteDialogOpen(open);
                            if (!open) setCommodityToDelete(null);
                          }}
                        >
                          <AlertDialogTrigger asChild>
                            <Button
                              variant="ghost"
                              size="icon"
                              onClick={() =>
                                setCommodityToDelete(commodity.goodsId)
                              }
                            >
                              <Trash2 className="h-4 w-4" />
                            </Button>
                          </AlertDialogTrigger>
                          <AlertDialogContent>
                            <AlertDialogHeader>
                              <AlertDialogTitle>确认删除</AlertDialogTitle>
                              <AlertDialogDescription>
                                确定要删除这个商品吗？此操作无法撤销。
                              </AlertDialogDescription>
                            </AlertDialogHeader>
                            <AlertDialogFooter>
                              <AlertDialogCancel>取消</AlertDialogCancel>
                              <AlertDialogAction
                                onClick={() =>
                                  commodityToDelete &&
                                  handleDeleteCommodity(commodityToDelete)
                                }
                              >
                                删除
                              </AlertDialogAction>
                            </AlertDialogFooter>
                          </AlertDialogContent>
                        </AlertDialog>
                      </TableCell>
                    </TableRow>
                  ))
                )}
              </TableBody>
            </Table>
          )}
        </CardContent>
      </Card>
    </div>
  );
}
